package keyfun.loaders 
{
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.display.Sprite;
	import keyfun.events.FileLoaderEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoaderDataFormat;
	/**
	 * ...
	 * @author Key Hui
	 */
	public class FileLoader extends Sprite
	{
		private var _loader:URLLoader = new URLLoader();
		private var _file:String;
		private var _fileData:Object;
		private var bytesLoaded:Number;
		private var bytesTotal:Number;
		public var isError:Boolean = false;
		
		public function FileLoader(file:String, format:String = URLLoaderDataFormat.TEXT) 
		{
			_file = file;
			_loader.dataFormat = format;
			addEvents(_loader);
			startLoad();
		}
		
		private function startLoad():void
		{
			_loader.load(new URLRequest(_file));
		}
		
		private function addEvents(dispatcher:IEventDispatcher):void
		{
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function removeEvents(dispatcher:IEventDispatcher):void
		{
			dispatcher.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.removeEventListener(Event.COMPLETE, completeHandler);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			removeEvents(_loader);
			isError = true;
			dispatchEvent(new FileLoaderEvent(FileLoaderEvent.ON_ERROR));
		}
		
		private function completeHandler(e:Event):void
		{
			removeEvents(_loader);
			_fileData = e.target.data;
			dispatchEvent(new FileLoaderEvent(FileLoaderEvent.ON_COMPLETE, {fileData:_fileData}));
		}
		
		private function progressHandler(e:ProgressEvent):void
		{
			bytesLoaded = e.bytesLoaded;
			bytesTotal = e.bytesTotal;
			dispatchEvent(new FileLoaderEvent(FileLoaderEvent.ON_LOADING, {bytesLoaded:bytesLoaded, bytesTotal:bytesTotal}));
		}
		
	}

}